package com.example.demo_text;

import user.User;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


public class UserDAO {

    // 独立创建日志记录器
    private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws SQLException, IOException, ClassNotFoundException {
        Properties prop = new Properties();
        prop.load(UserDAO.class.getClassLoader().getResourceAsStream("db.properties"));

        String driverClass = prop.getProperty("driverClassName");
        String originalJdbcUrl = prop.getProperty("url");
        String user = prop.getProperty("username");
        String password = prop.getProperty("password");

        // 修改 jdbcUrl，添加 allowPublicKeyRetrieval=true 和 useSSL=false 参数
        String jdbcUrl = originalJdbcUrl + (originalJdbcUrl.contains("?") ? "&" : "?")
                + "allowPublicKeyRetrieval=true&useSSL=false";

        Class.forName(driverClass);
        return DriverManager.getConnection(jdbcUrl, user, password);
    }


    /**
     * 检查用户名是否已存在
     */
    public static boolean checkUsernameExists(String username) {
        String sql = "SELECT COUNT(*) FROM login WHERE username = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    int count = rs.getInt(1);
                    return count > 0;
                }
            }
        } catch (SQLException | IOException | ClassNotFoundException e) {
            logger.error("数据库查询异常", e);
        }
        return false;
    }

    /**
     * 注册新用户，并返回完整的 User 对象
     *
     * @param username       用户名
     * @param password       密码
     * @param passwordAgain  确认密码
     * @param email          邮箱
     * @param age            年龄
     * @return User 注册成功返回用户对象，失败返回 null
     */
    // com.example.demo_text.UserDAO#registerUser()

    public static User registerUser(String username, String password, String passwordAgain,
                                    String email, int age, String usertype) {

        // 校验两次密码是否一致
        if (!password.equals(passwordAgain)) {
            logger.error("注册失败：两次输入的密码不一致");
            return null;
        }

        // 如果 userType 为空，则默认设为 "student"
        if (usertype == null || usertype.trim().isEmpty()) {
            usertype = "student";
        }

        String sql = "INSERT INTO login (username, password, email, age, user_type) VALUES (?, ?, ?, ?, ?)";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            stmt.setString(1, username);
            String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
            stmt.setString(2, hashedPassword);
            stmt.setString(3, email);
            stmt.setInt(4, age);
            stmt.setString(5, usertype); // 设置用户类型

            int rowsAffected = stmt.executeUpdate();

            if (rowsAffected > 0) {
                // 获取生成的自增 id
                try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        int userId = generatedKeys.getInt(1);

                        // 构造并返回完整的 User 对象
                        User user = new User();
                        user.setId(userId);
                        user.setUsername(username);
                        user.setEmail(email);
                        user.setAge(age);
                        user.setUserType(usertype); // 设置用户类型
                        return user;
                    }
                }
            }

        } catch (Exception e) {
            logger.error("数据库插入异常", e);
        }

        return null;
    }


    /**
     * 登录验证
     */

    // com.example.demo_text.UserDAO#login()

    public static User login(String username, String password) throws SQLException, IOException, ClassNotFoundException {
        String sql = "SELECT id, password, email, age, user_type FROM login WHERE username = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    int id = rs.getInt("id");
                    String storedPassword = rs.getString("password");
                    String email = rs.getString("email");
                    int age = rs.getInt("age");
                    String userType = rs.getString("user_type"); // 获取用户类型

                    if (BCrypt.checkpw(password, storedPassword)) {
                        User user = new User();
                        user.setId(id);
                        user.setUsername(username);
                        user.setPassword(storedPassword);
                        user.setEmail(email);
                        user.setAge(age);
                        user.setUserType(userType); // 设置用户类型
                        return user;
                    }
                }
            } catch (SQLException e) {
                logger.error("数据库查询异常", e);
            }
        }
        return null;
    }



    /**
     * 更新用户信息（邮箱、年龄）
     */
    public static boolean updateUserProfile(String username, String newEmail, int newAge) {
        String sql = "UPDATE login SET email = ?, age = ? WHERE username = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, newEmail);
            stmt.setInt(2, newAge);
            stmt.setString(3, username);

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (Exception e) {
            logger.error("更新用户信息失败", e);
        }
        return false;
    }

    // UserDAO.java 添加如下方法

    public static List<User> getAllStudents() {
        List<User> students = new ArrayList<>();
        String sql = "SELECT id, username, email, age FROM login WHERE user_type != 'admit'";

        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                User student = new User();
                student.setId(rs.getInt("id"));
                student.setUsername(rs.getString("username"));
                student.setEmail(rs.getString("email"));
                student.setAge(rs.getInt("age"));
                students.add(student);
            }

        } catch (Exception e) {
            logger.error("获取学生列表失败", e);
        }
        return students;
    }

/**
 * 根据课程ID获取课程名称
 */
public static String getCourseNameById(String courseIdStr) {
    if (courseIdStr == null || courseIdStr.trim().isEmpty()) {
        return "";
    }

    int courseId;
    try {
        courseId = Integer.parseInt(courseIdStr);
    } catch (NumberFormatException e) {
        // 参数不是有效的整数
        return "";
    }

    String sql = "SELECT course_name FROM course WHERE course_id = ?";
    try (Connection conn = UserDAO.getConnection();
         PreparedStatement stmt = conn.prepareStatement(sql)) {

        stmt.setInt(1, courseId);
        try (ResultSet rs = stmt.executeQuery()) {
            if (rs.next()) {
                return rs.getString("course_name");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return ""; // 没有找到返回空字符串
}

    /**
     * 根据用户ID获取用户信息
     *
     * @param id 用户ID
     * @return User 如果找到返回对应的 User 对象，否则返回 null
     */
    public static User getUserById(int id) {
        String sql = "SELECT id, username, email, age, user_type FROM login WHERE id = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, id);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    User user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setEmail(rs.getString("email"));
                    user.setAge(rs.getInt("age"));
                    user.setUserType(rs.getString("user_type")); // 设置用户类型
                    return user;
                }
            }
        } catch (Exception e) {
            logger.error("根据ID查询用户失败", e);
        }

        return null;
    }

    /**
     * 更新学生信息（邮箱、年龄）
     */
    /**
     * 更新学生信息（用户名、邮箱、年龄）
     */
    public static boolean updateStudentProfile(int id, String newUsername, String newEmail, int newAge) {
        String sql = "UPDATE login SET username = ?, email = ?, age = ? WHERE id = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, newUsername);
            stmt.setString(2, newEmail);
            stmt.setInt(3, newAge);
            stmt.setInt(4, id);

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (Exception e) {
            logger.error("更新学生信息失败", e);
        }
        return false;
    }

    public static List<User> getAllTeachers() {
        List<User> teachers = new ArrayList<>();
        String sql = "SELECT id, username, email, age FROM login WHERE user_type = 'teacher'";

        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                User teacher = new User();
                teacher.setId(rs.getInt("id"));
                teacher.setUsername(rs.getString("username"));
                teacher.setEmail(rs.getString("email"));
                teacher.setAge(rs.getInt("age"));
                teachers.add(teacher);
            }

        } catch (Exception e) {
            logger.error("获取教师列表失败", e);
        }
        return teachers;
    }

    public static boolean updateTeacherProfile(int id, String newUsername, String newEmail, int newAge) {
        return updateStudentProfile(id, newUsername, newEmail, newAge); // 和学生更新方法一致
    }
}


